<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库名称">
              <j-search-select-tag type="list" v-model="queryParam.warehouse" dict="hz_wms_warehouse_info,name,id,wms,status='Y'" placeholder="请选择可用仓库" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="分区名称">
              <a-input placeholder="请输入分区名称或代码" v-model="queryParam.partitionName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="库位查询">
              <a-input placeholder="请输入库位进行模糊查询" v-model="queryParam.locationCode"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="库位状态">
                <j-dict-select-tag placeholder="请选择库位状态" v-model="queryParam.status" dict-code="is_enable" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" v-has="'shelvesLocation:add'" type="primary">创建分区库位</a-button>
      <a-button @click="adjustPriority" v-has="'shelvesLocation:adjustPriority'" type="primary">调整优先级</a-button>
      <a-button @click="handlePrintBatch" v-has="'shelvesLocation:print'"  type="primary">批量打印</a-button>
      <a-button type="primary" v-has="'shelvesLocation:enable'" @click="changeEnable('Y', selectionRows, 1)">批量启用</a-button>
      <a-button type="danger" v-has="'shelvesLocation:enable'" @click="changeEnable('N', selectionRows, 1)">批量禁用</a-button>
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div> -->
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow="selectRowData"
      >
        <!-- 创建时间 -->
        <span slot="createTimeSlot" slot-scope="text, record"> {{ text }} &nbsp;{{ record.createBy }} </span>
        <span slot="action" slot-scope="text, record">
          <a v-if="record.status === 'N'" v-has="'shelvesLocation:enable'" @click="changeEnable('Y', record, 2)">启用</a>
          <!-- 启用状态可以禁用 -->
          <a v-if="record.status === 'Y'" v-has="'shelvesLocation:enable'" style="color: red" @click="changeEnable('N', record, 2)">禁用</a>
          <a-divider v-has="'shelvesLocation:enable'" type="vertical" />
          <a v-has="'shelvesLocation:print'" @click="printHandle([record])">打印标签</a>
          <!-- <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown> -->
        </span>
      </a-table>
    </div>

    <shelves-location-modal ref="modalForm" @ok="modalFormOk"></shelves-location-modal>
    <shelves-location-adjust-modal ref="adjustRef" @ok="modalFormOk"></shelves-location-adjust-modal>

    <!-- <div style="width: 0; height: 0; overflow: hidden"> -->
      <!-- <div style="width: 0; height: 0; overflow: hidden">
      <vue-easy-print  ref="easyPrint">
      <section ref="printRef" id="printContent" class="printContent">
        <div class="myPrint">
          <div class="pageWarp" v-for="(item,index) in locationCodeData" :key="index">
            <div class="locationCode">
              <div style="text-align: center">
                <div> <img :src="item.qrCode" width="28px" height="28px" /></div> 
               <div> {{item.priorityLevel}}</div>
              </div>
              <div class="locationCode-right">
                <div>
                <div>{{item.locationCode}}</div>
                <div>{{ item.partitionName }}</div> 
              </div>
            </div>
            </div>
          </div>
        </div>
      </section>
    </vue-easy-print>
    </div> -->
  </a-card>
</template>

<script>
import Vue from 'vue'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import ShelvesLocationModal from './modules/ShelvesLocationModal'
import ShelvesLocationAdjustModal from './modules/ShelvesLocationAdjustModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
// import VueEasyPrint from 'vue-easy-print'
import { getAction,postFormAction  } from '@/api/manage'
import { simpleDebounce } from '@/utils/util'
import { ACCESS_TOKEN, USER_INFO } from "@/store/mutation-types"
import { EventBus } from './modules/eventBus'
import { getLodop } from "@/utils/lodopPrint"
export default {
  name: 'ShelvesLocationList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    ShelvesLocationAdjustModal,
    ShelvesLocationModal,
  },
  data() {
    return {
      description: '仓库货架库位管理页面',
      printMode: false,
      locationCodeData:[],   //库位码数据
      socket1:'',
      socket2:'',
      // 表头
      columns: [
        {
          title: 'NO',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '仓库名称',
          align: 'center',
          dataIndex: 'warehouseId_dictText',
        },
        {
          title: '分区名称',
          align: 'center',
          dataIndex: 'partitionName',
        },
        {
          title: '分区代码',
          align: 'center',
          dataIndex: 'partitionCode',
        },
        {
          title: '货架代码',
          align: 'center',
          dataIndex: 'shelvesCode',
        },
        {
          title: '库位优先级',
          align: 'center',
          dataIndex: 'priorityLevel',
        },
        {
          title: '库位代码',
          align: 'center',
          dataIndex: 'locationCode',
        },
        {
          title: '库位状态',
          align: 'center',
          dataIndex: 'status_dictText',
          customCell: (record, index) => {
            if (record.status === 'Y') {
              return { style: { color: '#1890FF' } }
            } else {
              return { style: { color: '#FF0000' } }
            }
          },
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTimeSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/shelves/shelvesLocation/list',
        delete: '/wms/shelves/shelvesLocation/delete',
        deleteBatch: '/wms/shelves/shelvesLocation/deleteBatch',
        exportXlsUrl: '/wms/shelves/shelvesLocation/exportXls',
        importExcelUrl: 'shelves/shelvesLocation/importExcel',
        getLabel:'/wms/shelves/shelvesLocation/getLabel',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  mounted(){
    this.createWS()
    this.createWS_autoPriority()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    selectRowData(record, index) {
      const that = this
      return {
        on: {
          dblclick: () => {
            this.handleDetail(record)
          },
        },
      }
    },
    //新增
    handleAdd() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '创建分区库位'
      this.$refs.modalForm.disableSubmit = false
    },
    adjustPriority() {
      this.$refs.adjustRef.title = '货架优先级'
      this.$refs.adjustRef.getLoadData()
    },
    //批量打印
    handlePrintBatch:simpleDebounce(function(){
      if(this.selectedRowKeys.length <1){
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.printHandle(this.selectionRows)
    }, 400),
    //打印
    // printHandle_Old(ids){
    //   getAction(this.url.getLabel,{ids}).then(res=>{
    //     if(res.success){
    //       res.result.map(item=>{
    //         item.qrCode = item.qrCode ? `data:image/png;base64,${item.qrCode}` :''
    //        })||[]
    //        this.locationCodeData=res.result
    //        this.$nextTick(()=>{
    //         this.$refs.easyPrint.print()
    //        })
    //     }else{
    //       this.$message.warning(res.message)
    //     }
    //   })
    // },
    printHandle(labelData){
      try {
        const LODOP = getLodop();
        if (!LODOP) {
          this.$message.warning("未检测到C-Lodop打印服务，请先安装！")
          return;
        }
          // 创建打印任务  
        LODOP.PRINT_INIT("标签打印");
        labelData.forEach((item, index) => {
          if (index > 0) {
             LODOP.NEWPAGE(); // 新标签页
          }  
        LODOP.SET_PRINT_PAGESIZE(1, '50mm', '20mm', ''); // 设置标签尺寸50*20mm
        // 添加二维码（左侧）
        LODOP.ADD_PRINT_BARCODE(5, 15, 65, 65, "QRCode",item.locationCode);
        LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",3)   //指定二维码版本3 最大值53个字符
        const priorityLevel=`<div style="height: 12px;overflow:hidden;font-size:12px;text-align:center">${item.priorityLevel}</div>`
        LODOP.ADD_PRINT_HTM(65,10,65,20,priorityLevel)
        // 添加文本内容（右侧）
        //库位码 分区名称
        const strHtml=`
        <div style="font-weight: bold;font-size:16px;text-align:center;overflow:hidden;">${item.locationCode }</div>
        <div style="height: 12px;overflow:hidden;font-size:12px;text-align:center">${item.partitionName}</div>
        `        
        LODOP.ADD_PRINT_HTM(20,70,120,60,strHtml)
        })
        // 打印预览
        LODOP.PREVIEW();
        //LODOP.PRINT();
      }catch (e) {
        console.error('打印出错:', e);
        alert('打印过程中出错: ' + e.message);
      }
    },
    //操作启用禁用
    changeEnable(checked, records, type) {
      const that = this
      if (!records || Object.keys(records).length === 0) {
        this.$message.warning('请选择数据!')
        return
      }
      let codes = ''
      if (type === 1) {
        //批量操作
        codes = records.map((item) => item.id).join(',')
      } else if (type === 2) {
        //单个操作
        codes = records.id
      }
      if (checked === 'N') {
        that.$confirm({
          title: '确定要禁用所选库位？',
          content: (
            <div>
              <div style="color: red">禁用后将导致库位无法被用于业务</div>
              <div style="color: #999999">你还要继续吗？</div>
            </div>
          ),
          okText: '继 续',
          onOk() {
            that.handlePost(checked, codes)
          },
          onCancel() {},
        })
      } else {
        that.handlePost(checked, codes)
      }
    },
    handlePost(checked, record) {
      postFormAction('/wms/shelves/shelvesLocation/changeEnable/', { isEnable: checked, ids: record }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
          this.selectedRowKeys = []
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    createWS() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      //拼接地址
      let userId = Vue.ls.get(USER_INFO).id
      let shelves_url =window._CONFIG['socketURL'].replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId + '_shelves'
      this.socket1 = new WebSocket(shelves_url)
      this.socket1.onopen=(event)=>{
        EventBus.$emit('websocket-onopen')
      }
      this.socket1.onmessage=(event)=>{
         // 收到消息时通过事件总线发送
         EventBus.$emit('websocket-message', JSON.parse(event.data))
      }
      this.socket1.onerror=(event)=>{
        EventBus.$emit('websocket-error', error)
      }
    },
    createWS_autoPriority(){
     //拼接地址
     let userId = Vue.ls.get(USER_INFO).id
      let url =window._CONFIG['socketURL'].replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId + '_autoPriority'
      this.socket2 = new WebSocket(url)
      this.socket2.onopen=(event)=>{
        EventBus.$emit('websocket-onopen2')
      }
      this.socket2.onmessage=(event)=>{
         // 收到消息时通过事件总线发送
         EventBus.$emit('websocket-message2', JSON.parse(event.data))
      }
      this.socket2.onerror=(event)=>{
        EventBus.$emit('websocket-error2', error)
      }
    },
      // 手动关闭连接
    closeConnection(code = 1000, reason = '用户主动关闭') {
      if (this.socket1 && this.socket1.readyState === WebSocket.OPEN) {
        this.socket1.close(code, reason)
      }
      if (this.socket2 && this.socket2.readyState === WebSocket.OPEN) {
        this.socket2.close(code, reason)
      }
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'partitionId', text: '分区', dictCode: '' })
      fieldList.push({ type: 'string', value: 'code', text: '库位代码', dictCode: '' })
      fieldList.push({ type: 'int', value: 'priorityLevel', text: '优先级', dictCode: '' })
      fieldList.push({ type: 'string', value: 'status', text: '库位状态', dictCode: 'is_enable' })
      this.superFieldList = fieldList
    },
  },
  destroyed(){
     this.closeConnection()
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';


.printContent .pageWarp {
  page-break-after: always; 
  color: #000000 !important;
  -webkit-tap-highlight-color: #000000 !important;
  font-size: 5px;
}
.printContent .myPrint {
  /* 打印的时候是否显示底色 */
  -webkit-print-color-adjust: exact;
}

.locationCode {
  display: flex;
  justify-content: center;
  text-align: center;
  position: relative;
  width: 100%;
}
.locationCode-right {
  margin-left: 5px;
  position: relative;
  top: 2px;
  height:28px;
  display:table-cell;
  vertical-align:middle;
  font-size: 6px;
  div{
    div:nth-child(1){
      font-size: 10px;
      font-weight: bold;
    }
  }
}
// .locationCode-bottom {
//   height: 20px;
// }
</style>
<!-- 打印预览时多一张空白页 -->
<style @media="printContent">

@page {
  size: auto;
}
html {
  background-color: #ffffff;
  height: auto;
}
</style>